#coding:utf-8
import datetime,os
from django.db import models
from django.contrib.auth.models import User
from manages import  *
from settings import UPLOAD_ROOT
from thumbs import ImageWithThumbsField
from utils import cache_get
from django.db.models import signals  
from django.db import transaction

#附件表
class Attachment(models.Model):
    user = models.ForeignKey(User)
    path = models.FileField(upload_to=UPLOAD_ROOT)
    status = models.BooleanField(default=False)
    def __unicode__(self):
        return u'%s' % (self.path,)      

#标签
class Tag(models.Model):
    name = models.CharField(max_length=128,unique=True)
    device_count = models.IntegerField(default=1)
    app_count = models.IntegerField(default=1)
    topic_count = models.IntegerField(default=1)
    group_count = models.IntegerField(default=1)
    
    def dev_count(self):
        return cache_get("mobeir_tag_%s_dev_count"%self.id,self.dev_tags.count(),60*10)
    
    def __unicode__(self):
        return unicode(self.name)
            
class City(models.Model):    
    name = models.CharField(max_length=32)
    code = models.CharField(max_length=6)
    
    def __unicode__(self):
        return u'%s %s' % (self.code, self.name)  
    
#徽章
class Badge(models.Model):
    name = models.CharField(max_length=192)
    image = models.FileField(upload_to=UPLOAD_ROOT,blank=True)
    credit = models.IntegerField()
    
    def __unicode__(self):
        return u'%s' % (self.name,)          
    
#评论
class Comment(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=256,blank=True)
    content = models.TextField()
    star = models.IntegerField(default=0)
    last_update = models.DateTimeField(default=datetime.datetime.now)
    replies = models.ManyToManyField("self",symmetrical=False,blank=True)
    
    objects = CommentManager()

    def __unicode__(self):
        return u'%s %s' % (self.title,self.last_update)         

#资源
class Link(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=512)
    url = models.URLField()
    
    def __unicode__(self):
        return u'%s' % (self.title,)  
    
class Audit(models.Model):    
    user = models.ForeignKey(User)
    status = models.BooleanField(default=False)
    
    def __unicode__(self):
        return u'%s %s' % (self.user,self.status)      
    
class Photo(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=128)
    summary = models.CharField(max_length=1024, blank=True)
    comments = models.ManyToManyField(Comment,related_name='photo_comments',blank=True)
    path = models.FileField(upload_to='upload/photo/%Y%m')
    privacy = models.CharField(max_length=32,
            choices=(("default",u"公开"),("private",u"私有")),default='default')
    
    def __unicode__(self):
        return u'%s %s' % (self.name,self.path,) 
    
class Video(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=128)
    summary = models.CharField(max_length=1024, blank=True)
    comments = models.ManyToManyField(Comment,related_name='video_comments',blank=True)
    url = models.URLField(blank=True)
    privacy = models.CharField(max_length=32,
            choices=(("default",u"公开"),("private",u"私有")),default='default')
    
    def __unicode__(self):
        return u'%s %s' % (self.name,self.path,)               
    
#日记
class Note(models.Model):
    user = models.ForeignKey(User)    
    content =  models.CharField(max_length=1024)
    comments = models.ManyToManyField(Comment,related_name='note_comments',blank=True)
    last_update = models.DateTimeField(default=datetime.datetime.now)
    privacy = models.CharField(max_length=32,
            choices=(("default",u"公开"),("private",u"私有")),default='default')
    
    def __unicode__(self):
        return u'%s' % (len(self.content)<=20 and self.content or self.content[:20],)      
        

       
#小组
class Group(models.Model):
    name = models.CharField(max_length=32)
    creater = models.ForeignKey(User)
    admins = models.ManyToManyField(User,related_name='g_admins',blank=True)
    summary = models.TextField(blank=True)
    tags = models.ManyToManyField(Tag,blank=True)
    privacy = models.CharField(max_length=32,
            choices=(("default",u"公开圈子"),("audit",u"加入需要审核"),("private",u"私有圈子加入需邀请")),
            default='default')
    gtype = models.CharField(max_length=32,
        choices=(("user",u"用户圈子"),("system",u"系统圈子")),default='user')
    audits =  models.ManyToManyField(Audit,related_name='g_audits',blank=True)
    status = models.BooleanField(default=False)
    create_date = models.DateTimeField(default=datetime.datetime.now)
    image = ImageWithThumbsField(upload_to=UPLOAD_ROOT, sizes=((125,125),),blank=True)
    photos = models.ManyToManyField(Photo,related_name='g_photos',blank=True)
    attachments = models.ManyToManyField(Attachment,related_name='g_attachments',blank=True)
    
    objects = GroupManager()   
 
    
    def __unicode__(self):
        return u'%s' % (self.name)   
    
    
        
#应用程序
class App(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(verbose_name=u"名称",max_length=192)
    version = models.CharField(verbose_name=u"版本",max_length=16,blank=True)
    pubdate = models.CharField(verbose_name=u"发布时间",max_length=24,blank=True)   
    app_url = models.URLField(verbose_name=u"软件主页",blank=True)
    auther = models.CharField(verbose_name=u"软件作者",max_length=192,blank=True)
    auther_url = models.URLField(verbose_name=u"作者主页",blank=True)
    last_update = models.DateTimeField(default=datetime.datetime.now)
    summary = models.TextField(verbose_name=u"简介",blank=True)
    image = ImageWithThumbsField(verbose_name=u"图片",upload_to=UPLOAD_ROOT, sizes=((125,125),),blank=True)
    audit = models.BooleanField(default=False)
    score = models.FloatField(default=0.0)
    group = models.ForeignKey(Group,null=True,blank=True)
    photos = models.ManyToManyField(Photo,related_name='app_photos',blank=True)
    links = models.ManyToManyField(Link,related_name='app_links',blank=True)
    comments = models.ManyToManyField(Comment,related_name='app_comments',blank=True)
    tags = models.ManyToManyField(Tag,related_name='app_tags',blank=True)
    
    def using(self):             
        return cache_get("mobeir_app_%s_using"%self.id,self.user_using_apps.count())
    def want(self):
        return cache_get("mobeir_app_%s_want"%self.id,self.user_want_apps.count())
    def follow(self):
        return cache_get("mobeir_app_%s_follow"%self.id,self.user_follow_apps.count())
    def rec(self):
        return cache_get("mobeir_app_%s_rec"%self.id,self.user_rec_apps.count())
    def like(self):
        return cache_get("mobeir_app_%s_like"%self.id,self.user_like_apps.count())    

    objects =AppManager() 
    
 
    def __unicode__(self):
        return u'%s' % (self.name,)      
    
#应用特性
class AppFeature(models.Model):
    user = models.ForeignKey(User)
    app = models.ForeignKey(App)
    content = models.CharField(max_length=1024)
    last_update = models.DateTimeField(default=datetime.datetime.now)

    def __unicode__(self):
        return u'%s %s' % (self.app,self.last_update)         
    
class AppStar(models.Model):
    user = models.ForeignKey(User)
    app = models.ForeignKey(App)
    value = models.IntegerField()
    star_time =  models.DateTimeField(default=datetime.datetime.now)     
     
#设备
class Device(models.Model):
    name = models.CharField(verbose_name=u"名称",max_length=128)
    creater = models.ForeignKey(User)
    pubdate = models.CharField(verbose_name=u"上市时间",max_length=24,blank=True)
    company = models.CharField(verbose_name=u"厂商",max_length=192,blank=True)
    company_url = models.URLField(verbose_name=u"厂商主页",blank=True)
    image = ImageWithThumbsField(verbose_name=u"图片",upload_to=UPLOAD_ROOT, sizes=((125,125),),blank=True)
    last_update = models.DateTimeField(default=datetime.datetime.now)
    summary = models.TextField(verbose_name=u"简介", blank=True)
    audit = models.BooleanField(default=False)
    score = models.FloatField(default=0.0)
    group = models.ForeignKey(Group,verbose_name=u"手机交流圈子",null=True,blank=True)
    photos = models.ManyToManyField(Photo,related_name='dev_photos',blank=True)
    tags = models.ManyToManyField(Tag,related_name='dev_tags',blank=True)
    links = models.ManyToManyField(Link,related_name='dev_links',blank=True)
    comments = models.ManyToManyField(Comment,related_name='dev_comments',blank=True)
    
    def using(self):
        return cache_get("mobeir_device_%s_using"%self.id,self.user_using_devices.count())
    def want(self):
        return cache_get("mobeir_device_%s_want"%self.id,self.user_want_devices.count())
    def follow(self):
        return cache_get("mobeir_device_%s_follow"%self.id,self.user_follow_devices.count())
    def rec(self):
        return cache_get("mobeir_device_%s_rec"%self.id,self.user_rec_devices.count())
    def like(self):
        return cache_get("mobeir_device_%s_like"%self.id,self.user_like_devices.count())


    def __unicode__(self):
        return u'%s' % (self.name,)  
    
class DeviceFeature(models.Model):
    user = models.ForeignKey(User)
    device = models.ForeignKey(Device)
    content = models.CharField(max_length=1024)
    last_update = models.DateTimeField(default=datetime.datetime.now)

    def __unicode__(self):
        return u'%s %s' % (self.device,self.last_update)        
    
class DeviceStar(models.Model):
    user = models.ForeignKey(User)
    device = models.ForeignKey(Device)
    value = models.IntegerField()
    star_time =  models.DateTimeField(default=datetime.datetime.now)         

     
#主题
class Topic(models.Model):
    group = models.ForeignKey(Group)
    user = models.ForeignKey(User)
    tags = models.ManyToManyField(Tag,blank=True)
    title = models.CharField(max_length=256)
    content = models.TextField()
    photos = models.ManyToManyField(Photo,related_name='topic_photos',blank=True)
    attachments = models.ManyToManyField(Attachment,related_name='topic_attachments',blank=True)
    comments = models.ManyToManyField(Comment,related_name='topic_comments',blank=True)
    last_update = models.DateTimeField(default=datetime.datetime.now)
    privacy = models.CharField(max_length=32,default='default')
    objects = TopicManager()

    def __unicode__(self):
        return u'%s' % (self.title,)          

#用户扩展信息
class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    city = models.ForeignKey(City,blank=True)
    status = models.CharField(max_length=512,blank=True)
    image = models.FileField(upload_to=UPLOAD_ROOT,blank=True)
    home = models.CharField(max_length=128, blank=True)
    credit = models.IntegerField(default=50)
    badges = models.ManyToManyField(Badge,related_name='user_badges',blank=True)
    summary = models.TextField(blank=True)
    activity = models.IntegerField(default=0)
    
    #手机关联数据
    using_devices = models.ManyToManyField(Device,related_name='user_using_devices',blank=True)
    used_devices = models.ManyToManyField(Device,related_name='user_used_devices',blank=True)
    like_devices = models.ManyToManyField(Device,related_name='user_like_devices',blank=True)
    want_devices = models.ManyToManyField(Device,related_name='user_want_devices',blank=True)
    follow_devices = models.ManyToManyField(Device,related_name='user_follow_devices',blank=True)
    rec_devices = models.ManyToManyField(Device,related_name='user_rec_devices',blank=True)
    
    like_dev_features =  models.ManyToManyField(DeviceFeature,related_name='user_like_dev_features',blank=True)
    unlike_dev_features =  models.ManyToManyField(DeviceFeature,related_name='user_unlike_dev_features',blank=True)
 
    like_app_features =  models.ManyToManyField(AppFeature,related_name='user_like_app_features',blank=True)
    unlike_app_features =  models.ManyToManyField(AppFeature,related_name='user_unlike_app_features',blank=True)
    
    #应用关联数据
    using_apps = models.ManyToManyField(App,related_name='user_using_apps',blank=True)
    used_apps = models.ManyToManyField(App,related_name='user_used_apps',blank=True)
    like_apps = models.ManyToManyField(App,related_name='user_like_apps',blank=True)
    want_apps = models.ManyToManyField(App,related_name='user_want_apps',blank=True)
    follow_apps = models.ManyToManyField(App,related_name='user_follow_apps',blank=True)
    rec_apps = models.ManyToManyField(App,related_name='user_rec_apps',blank=True)
    
    #组关联数据
    join_groups = models.ManyToManyField(Group,related_name='user_join_groups',blank=True)
    rec_groups = models.ManyToManyField(Group,related_name='user_rec_groups',blank=True)
    follow_groups = models.ManyToManyField(Group,related_name='user_follow_groups',blank=True)
    
    #主题关联数据
    like_topics = models.ManyToManyField(Topic,related_name='user_like_topics',blank=True)
    rec_topics = models.ManyToManyField(Topic,related_name='user_rec_topics',blank=True)
    retopics = models.ManyToManyField(Topic,related_name='user_reply_topics',blank=True)
    aboutme_topics = models.ManyToManyField(Topic,related_name='user_aboutme_topics',blank=True)
    subscribe_topics = models.ManyToManyField(Topic,related_name='user_subscribe_topics',blank=True)
    
    like_comments = models.ManyToManyField(Comment,related_name='user_like_comments',blank=True)
    unlike_comments = models.ManyToManyField(Comment,related_name='user_unlike_comments',blank=True)
    
    like_links = models.ManyToManyField(Link,related_name='user_like_links',blank=True)
    unlike_links = models.ManyToManyField(Link,related_name='user_unlike_links',blank=True)    
    
    like_note = models.ManyToManyField(Note,related_name='user_like_notes',blank=True)
    re_note = models.ManyToManyField(Note,related_name='user_re_notes',blank=True)
    
    follows = models.ManyToManyField(User,related_name='user_follows',blank=True)
    blocks = models.ManyToManyField(User,related_name='user_blocks',blank=True)
    following = models.ManyToManyField(User,related_name='user_following',blank=True)
    
    objects = UserManager()
    
    def get_cache_user(self):
        return cache_get('mobeir_user_%s'%self.user_id,self.user)
    
    def __unicode__(self):
        return unicode(self.user.username)      



#消息
class Message(models.Model):
    title = models.CharField(max_length=765)
    sender = models.ForeignKey(User)
    receiver = models.ForeignKey(User,related_name='msg_receiver')
    sendtime = models.DateTimeField(default=datetime.datetime.now)
    content =  models.TextField()
    isread = models.IntegerField()
    sdelete = models.IntegerField()
    rdelete = models.IntegerField()

    def __unicode__(self):
        return u'%s' % (self.title,)      



def update_activity(sender, instance, signal, *args, **kwargs):
    try:
        user = instance.user.get_profile()
        user.activity += 1
        user.save() 
        transaction.commit()
    except:
        pass
    
     
signals.post_save.connect(update_activity, sender=Topic)    
signals.post_save.connect(update_activity, sender=Comment)   
signals.post_save.connect(update_activity, sender=Photo)   
signals.post_save.connect(update_activity, sender=Video)    
signals.post_save.connect(update_activity, sender=Note)   
    


